import { parseRule } from './parser'
import { load } from 'cheerio'
import { trim, startsWith } from 'lodash'
import { request as _request } from './request'
import { parseSearchUrl, v2 as _v2 } from './common'

function parseContent (source: any, doc: string) {
  if (source.ruleSearch) {
    return v3.parseContent(source, doc)
  } else {
    return v2.parseContent(source, doc)
  }
}

async function downloadContent (source: any, url: string) {
  if (source.ruleSearch) {
    return v3.downloadContent(source, url)
  } else {
    return v2.downloadContent(source, url)
  }
}

const v3 = {
  parseContent (source: any, doc: string) {
    const $ = load(doc, { decodeEntities: false })

    const bookMap = source.ruleContent

    const item: Record<string, string> = {}
    Object.keys(bookMap).forEach(prop => {
      item[prop] = trim(parseRule(bookMap[prop], $) as string)
    })

    return item
  },

  async  downloadContent (source: any, url: string) {
    if (!startsWith(url, 'http')) {
      url = source.bookSourceUrl + url
    }
    const { options } = parseSearchUrl(source)
    return _request(url, options)
  }
}

const v2 = {
  parseContent (source: any, doc: string) {
    const $ = load(doc, { decodeEntities: false })

    const bookMap: Record<string, string> = {
      content: 'ruleBookContent'
    }

    const item: Record<string, string> = {}
    Object.keys(bookMap).forEach(prop => {
      item[prop] = trim(parseRule(source[bookMap[prop]], $) as string)
    })

    return item
  },

  async  downloadContent (source: any, url: string) {
    if (!startsWith(url, 'http')) {
      url = source.bookSourceUrl + url
    }
    const { options } = _v2.parseSearchUrl(source)
    return _request(url, options)
  }
}

export {
  parseContent,
  downloadContent
}
